import { createLogger, transports, format } from 'winston';
import 'winston-daily-rotate-file';
import { presets } from 'winston-humanize-formatter';

export const logger = createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: process.env.NODE_ENV === 'development' ? presets.cli.dev : presets.cli.prod,
  transports: (() => {
    //开发环境下输出到控制台
    if (process.env.NODE_ENV === 'development') {
      return [
        new transports.Console({
          format: format.combine(format.timestamp(), format.ms()),
        }),
      ];
    }

    if (process.env.NODE_ENV === 'production') {
      return [
        // 记录错误日志
        new transports.DailyRotateFile({
          level: 'error',
          dirname: `logs/errors`,
          filename: `%DATE%-error.log`,
          datePattern: 'YYYY-MM-DD',
          maxSize: '20m',
        }),
        new transports.DailyRotateFile({
          dirname: `logs/infos`,
          filename: `%DATE%-combined.log`,
          datePattern: 'YYYY-MM-DD',
          maxSize: '20m',
          format: format.combine(
            format((info) => {
              if (info.level === 'error') {
                return false; // 过滤掉'error'级别的日志
              }
              return info;
            })(),
            format.timestamp(),
            format.ms(),
          ),
        }),
      ];
    }
    return [];
  })(),
});
